package com.czkevin.biliwsclient;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.nio.charset.StandardCharsets;

public class LiveBan {

  public static String ENDPOINT_BAN_USER = "https://api.live.bilibili.com/banned_service/v2/Silent/add_block_user";

  public final String room;

  public final String uuid;

  public final String session;

  public final String jct;

  public final String fmt;

  public LiveBan(String room, String uuid, String session, String jct, String fmt) {
    this.room = room;
    this.uuid = uuid;
    this.session = session;
    this.jct = jct;
    this.fmt = fmt;
  }

  /**
   * 封禁用户
   * @param uid uid
   * @param hours 1-720小时
   * @return
   */
  public boolean banUser(int uid, int hours) {
    if(hours < 1) {
      hours = 1;
    }
    if(hours > 720) {
      hours = 720;
    }
    final String body =
        fmt.replace("__UID__", Integer.toString(uid)).replace("__HOURS__", Integer.toString(hours));
    try {
      final String ret = HTTPHelper.doPost(ENDPOINT_BAN_USER, null, body.getBytes(StandardCharsets.UTF_8), (conn) -> {
        conn.setRequestProperty("referer", String.format("https://live.bilibili.com/%s", room));
        conn.setRequestProperty("accept-language", "en,zh-CN;q=0.9,zh;q=0.8");
        conn.setRequestProperty("cookie", String.format("_uuid=%s; bili_jct=%s; SESSDATA=%s; ", uuid, jct, session));
      });
      JSONObject data = JSON.parseObject(ret);
      if(data.containsKey("code") && data.getIntValue("code") == 0) {
        return true;
      } else {
        throw new IllegalStateException("server fail: " + ret);
      }
    } catch (Exception ex) {
      ex.printStackTrace();
      return false;
    }
  }

}
